import { flowType, userType } from '@/components/MiniBpmn/types';
import UserSelector, { type IUserSelectorView } from '..';
import BaseControlService from '../../base/service';
import { type IBaseSelector, type ISelectorOption } from '../selector/base';
import DefaultCcService from './selector/interpreter/service';

class CCUserSelectorService extends BaseControlService implements IUserSelectorView {
  label: string = '';

  value: string = userType.user;

  selector?: IBaseSelector;

  selectors: ISelectorOption[] = [];
  selectorsMap :Record<string,IBaseSelector>= {};

  interpreter = new DefaultCcService('');

  constructor({ label, selectors }: { label: string, selectors: ISelectorOption[] }) {
    super();
    this.label = label;
    this.selectors = selectors;
  }

  onChange(value: string) {
    this.value = value;
    this.updateProperties(value);
    this.initSelector(value);
  }

  updateProperties(value: string) {
    // const element = this.panel.getElement();
    // this.root.getModeling().updateProperties(
    //   element,
    //   {
    //     'flowable:dataType': value,
    //     // // 清空
    //     // 'flowable:candidateGroups': '',
    //     // 'flowable:text': ''
    //   },
    // );
    //  清空
    this.interpreter.onChange([]);
  }

  getSelector(type: string) {
    if(this.selectorsMap[type]){
      return this.selectorsMap[type];
    }else{
      // 初始化
      const Selector = this.selectors.find(item => item.value === type);

      if (Selector) {
        this.selectorsMap[type] = new Selector.Service();
      } else {
        throw new Error(`未找到${type}对应的选择器`);
      }
      return this.selectorsMap[type];
    }
  }

  initSelector(value: string) {
    const selector = this.getSelector(value);
    this.selector = selector;
    if (selector) {
      selector.bindBpmnService(this.root);
      selector.bindPanelService(this.panel);
      selector.init();
      selector?.onShow?.();
    }
  }

  init(): void {
    // const type: string = this.panel.getElement().businessObject.$attrs['flowable:dataType'];
    this.value = this.selectors[0]?.value;

    const element = this.panel.getElement();
    const extensionElements = element.businessObject.extensionElements;
    const dom = extensionElements?.values?.find((e: any) => e.$type === `flowable:DefaultCc`);
    this.value = dom?.type || userType.user;

    this.initSelector(this.value);
    this.interpreter.bindBpmnService(this.root);
    this.interpreter.bindPanelService(this.panel);
  }

  onShow(): void {
    this.selector?.onShow?.();
  }

  isShowInitiator: boolean = false;
  component = UserSelector;
}

export default CCUserSelectorService;
